﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using Microsoft.Practices.Unity;
using DreamBuilder.UI.UserControls.DataAccess.Services;
using DreamBuilder.Core.Container;
using System.Data;

namespace Web
{
    public partial class ImageCutAndPrint : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                    if (!IsPostBack)
                    {
                        string path = Path.Combine(this.Request.PhysicalApplicationPath, "TempDatas");
                        path = Path.Combine(path, this.Session.SessionID);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                    }
                    if (!string.IsNullOrEmpty(this.Request.QueryString["mode"]) && this.Request.QueryString["mode"].ToLower() == "fromwebpage")
                    {
                        try
                        {
                            string imgSrc = this.Request.QueryString["imgSrc"];
                            if (string.IsNullOrEmpty(imgSrc))
                            {
                                throw new Exception("imgSrc is null");
                            }
                            int selectHeight = 0;
                            int selectWidth = 0;
                            int selectedImgLeft = 0;
                            int selectedImgTop = 0;
                            int selectedImgWidth = 0;
                            int selectedImgHeight = 0;
                            selectHeight = Convert.ToInt32(double.Parse(this.Request.QueryString["selectHeight"]));
                            selectWidth = Convert.ToInt32(double.Parse(this.Request.QueryString["selectWidth"]));
                            selectedImgLeft = Convert.ToInt32(double.Parse(this.Request.QueryString["selectedImgLeft"]));
                            selectedImgTop = Convert.ToInt32(double.Parse(this.Request.QueryString["selectedImgTop"]));
                            selectedImgWidth = Convert.ToInt32(double.Parse(this.Request.QueryString["selectedImgWidth"]));
                            selectedImgHeight = Convert.ToInt32(double.Parse(this.Request.QueryString["selectedImgHeight"]));

                            Uri uri = new Uri(imgSrc);
                            string imgPath = this.Context.Server.MapPath(uri.AbsolutePath);
                            string tempImgPath = this.Request.PhysicalApplicationPath + "\\TempDatas\\" + this.Session.SessionID + "\\" + String.Concat(Guid.NewGuid()) + Path.GetExtension(imgPath);
                            File.Copy(imgPath, tempImgPath);
                            Bitmap orginalImage = new Bitmap(tempImgPath);
                            Bitmap newBitImage = new Bitmap(selectedImgWidth, selectedImgHeight);
                            Graphics g1 = Graphics.FromImage(newBitImage);
                            g1.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            g1.DrawImage(orginalImage, new Rectangle(0, 0, selectedImgWidth, selectedImgHeight), new Rectangle(0, 0, orginalImage.Width, orginalImage.Height), GraphicsUnit.Pixel);
                            g1.Dispose();
                            Bitmap outputImage = new Bitmap(selectWidth, selectHeight, PixelFormat.Format24bppRgb);
                            Graphics g2 = Graphics.FromImage(outputImage);
                            g2.DrawImage(newBitImage, new Rectangle(0, 0, selectWidth, selectHeight), new Rectangle(selectedImgLeft, selectedImgTop, selectWidth, selectHeight), GraphicsUnit.Pixel);
                            g2.Dispose();
                            string outputImagePath = this.Request.PhysicalApplicationPath + "\\TempDatas\\" + this.Session.SessionID + "\\" + String.Concat(Guid.NewGuid()) + Path.GetExtension(imgPath);
                            outputImage.Save(outputImagePath);
                            this.selectedImg.ImageUrl = "TempDatas/" + this.Session.SessionID + "/" + Path.GetFileName(outputImagePath);
                            //this.OrginalImagePath.Value = this.Request.QueryString["OrginalImagePath"];
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    else if (!string.IsNullOrEmpty(this.Request.QueryString["mode"]) && this.Request.QueryString["mode"].ToLower() == "fromserver")
                    {
                        if (string.IsNullOrEmpty(this.Request.QueryString["DBHelperString"]))
                        {
                            throw new Exception("DBHelperString is null");
                        }
                        if (string.IsNullOrEmpty(this.Request.QueryString["AttachmentId"]))
                        {
                            throw new Exception("AttachmentId is null");
                        }
                        AttachmentDAL AttachmentDAL = UContainer.Resolve<AttachmentDAL>();
                        AttachmentDAL.AttachmentDBHelperString = this.Request.QueryString["DBHelperString"];
                        DataTable oDataTable = AttachmentDAL.GetAttachmentByID(this.Request.QueryString["AttachmentId"]);
                        if (oDataTable != null && oDataTable.Rows.Count>0)
                        {
                            byte[] attachmentContent = (byte[])oDataTable.Rows[0]["AttachmentContent"];
                            string documentType = (string)oDataTable.Rows[0]["DocumentType"];
                            string tempFileName = string.Concat(Guid.NewGuid())+"."+documentType;
                            string tempFilePath = this.Request.PhysicalApplicationPath + "\\TempDatas\\" + this.Session.SessionID + "\\" + tempFileName;
                            using(System.IO.FileStream fs = new FileStream(tempFilePath,FileMode.Create))
                            {
                                fs.Write(attachmentContent,0,attachmentContent.Length);
                                fs.Close();
                            }
                            this.selectedImg.ImageUrl = "TempDatas/" + this.Session.SessionID + "/" + tempFileName;

                            //this.OrginalImagePath.Value = tempFileName;
                        }
                    }
                    else if(!string.IsNullOrEmpty(this.Request.QueryString["mode"]) && this.Request.QueryString["mode"].ToLower() == "reback")
                    {
                        this.selectedImg.ImageUrl = "TempDatas/" + this.Session.SessionID + "/" + this.Request.QueryString["OrginalImagePath"];
                        //this.OrginalImagePath.Value = this.Request.QueryString["OrginalImagePath"];
                    }
                    else
                    {
                        throw new Exception("QueryString Error");
                    }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}